# -*- coding: utf-8 -*-
import json
import logging
import re
import datetime

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.core.urlresolvers import reverse
from django.views.generic import View
from django.forms.models import modelformset_factory, modelform_factory
from django.core.mail import send_mass_mail, send_mail
from django.core.mail import EmailMultiAlternatives
from django.contrib.sessions.backends.db import Session
from django.conf import settings
from django.utils import timezone
from django.core import serializers

from forms import *
from models import *
from services import UserService, UserPrivateService

from common.services import SendMessage
from common.functions import *
from app.services import UserLoginDecorator
from utils.code_msg import codeMsg


# Create your views here.


# 用户登录
def login(request):
    if request.method != 'POST':
        return JsonResponse({'status': 'error', 'msg': 'method_error'})

    user = UserService()
    user_login = user.login(request.POST.get('username'), request.POST.get('password'))
    if user_login is False:
        return JsonResponse(dict({
            'status': False,
        }, **codeMsg['username_error']))

    request.token_store['user_id'] = user.user.id
    request.token_store['user_nickname'] = user.user.nickname

    user.user.lasttime = datetime.datetime.now(pytz.timezone('Asia/Shanghai'))
    user.edit_user()
    return JsonResponse(dict({
        'status': True,
        'data': {
            'user_id': user.user.id,
            'user_nickname': user.user.nickname
        }
    }, **codeMsg['login_success']))


def register(request):
    """
    用户注册，先注册然后验证账号
    """
    if request.method != 'POST':
        return JsonResponse({'status': 'error', 'msg': 'method_error'})
    user = UserService()
    create_user = user.create_user(request.POST.copy())
    if create_user.get('status') is True:
        del create_user['msg']
        return JsonResponse(dict(
            create_user,
            **codeMsg['register_success']
        ))
    else:
        create_user['data'] = functions.get_form_errors(create_user.get('msg'))
        del create_user['msg']
        return JsonResponse(dict(
            create_user,
            **codeMsg['register_error']
        ))


def mailbox(request, email, uid):
    """
    验证邮箱
    """
    user = UserService()
    if user.verification_email(uid=uid, email=email):
        return render(request, 'people/mailbox.html')
    else:
        return render(request, 'people/error.html')


class VerificationView(View):
    """
    找回密码, 需要验证邮箱或是手机号，发送验证码
    """
    get_template_name = 'people/get_mailbox.html'
    post_template_name = 'people/success.html'
    reset_template_name = 'people/reset.html'

    def get(self, request, *args, **kwargs):
        """
        填写邮箱或手机号，密码，获取验证码
        """
        method = request.GET.get('method', None)
        if method is None:
            return render(request, self.get_template_name)
        elif method == 'reset':
            return render(request, self.reset_template_name)

    def post(self, request, *args, **kwargs):
        """
        接收邮箱或手机号，验证码，密码进行数据库更新
        """
        email = request.POST.get('email', None)
        method = request.POST.get('method', None)
        user = UserService()
        user.get_user_by_email(email)
        if method is None and user.user is not None:
            # todo 发送验证码
            return render(request, self.post_template_name)
        elif method == 'reset' and user.user is not None:
            # todo 重置密码
            return render(request, self.post_template_name)


def logout(request):
    try:
        uid = request.POST.get('uid')
        user = UserService()
        user.get_user(uid=uid)
        user.logout()
        request.session = None
        # request.session.flush()
    except Exception as e:
        print str(e)
    return JsonResponse({'status': 'success', 'msg': ''})


@UserLoginDecorator.login_require
def real_name(request):
    """
    实名验证，需要上传身份证
    """
    if request.method != 'POST':
        return JsonResponse({'status': 'error', 'msg': 'method_error'})
    photo_front = request.POST.get('photo_front', None)
    photo_back = request.POST.get('photo_back', None)
    id_card = request.POST.get('id_card', None)
    uid = request.token_store.get('user_id')
    user = UserService()
    result = user.real_name(uid, id_card, photo_front, photo_back)
    if result.get('status', False):
        return JsonResponse({'status': 'success', 'msg': ''})
    return JsonResponse({'status': 'error', 'msg': result.get('msg')})


@UserLoginDecorator.login_require
def user_detail(request):
    """
    获取用户的个人信息
    """
    uid = request.token_store.get('user_id')
    user = UserService()
    user.get_user(uid)
    if user.user is None:
        return JsonResponse({'status': 'error', 'msg': 'error_user'})
    msg = model_to_dict(user.user)
    del msg['password']
    msg['nicklogo'] = str(msg['nicklogo'])
    return JsonResponse({'status': True, 'data': msg, 'message': '', 'code': 200})


@UserLoginDecorator.login_require
def amount(request):
    user_id = request.token_store.get('user_id')
    user_private = UserPrivateService.get_user_private(user_id)
    if user_private is not None:
        return JsonResponse({
            'status': True,
            'data': user_private,
            'code': 200,
            'message': '',
        })
    return JsonResponse({
        'status': False,
        'data': '',
        'code': 500,
        'message': '',
    })
